/*
   Copyright 2011 James Bowling

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package com.armedia.dctm.constraints.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.junit.After;
import org.junit.Before;

import com.armedia.dctm.constraints.Constraint;
import com.armedia.dctm.constraints.ConstraintException;
import com.armedia.dctm.constraints.test.SessionFactory.ParamName;
import com.documentum.fc.client.IDfPersistentObject;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.common.DfException;

public abstract class AbstractTestCase {
	
	protected IDfSession session;
	
	protected boolean transactional = true;

	@Before
	public void setUp() throws Exception {
		String password = System.getProperty(ParamName.password.toString());
		if (password == null || password.length() == 0) {
			password = prompt("Please type the password and press enter:");
			System.setProperty(ParamName.password.toString(), password);
		}
		session = SessionFactory.getInstance().getSession();
		if (isTransactional()) {
			session.beginTrans();
		}
	}

	@After
	public void tearDown() throws Exception {
		if (isTransactional()) {
			session.abortTrans();
		}
	}

	protected IDfSession getSession() {
		return this.session;
	}
	
	String prompt(String prompt) throws IOException {
		System.out.print(prompt);
		final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		return reader.readLine();
	}

	public boolean isTransactional() {
		return transactional;
	}

	public void setTransactional(boolean transactional) {
		this.transactional = transactional;
	}

	protected boolean check(final IDfPersistentObject po, final Constraint constraint) throws DfException {
		boolean exceptionThrown = false;
		try {
			constraint.check(po);
		} catch (ConstraintException e) {
			exceptionThrown = true;
		}
		return exceptionThrown;
	}	

}
